<?php
namespace app\api\controller\orderhawa;
use think\File;
use think\facade\Env;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderdata\Goods;
use app\common\model\quotation\QuotationList;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderhawa\Hawa;
use app\api\controller\Base;
use app\common\model\cost\Costtype;
use app\common\model\cost\Pay;
use app\common\model\cost\Revenue;
use app\common\model\power\Rolepower;
use app\api\controller\mytool\Sendmessage;
use app\api\controller\revenue_ap\Raplist;
use app\common\model\revenue_ap\Raplist as RaplistModel;
class Orderhawaacco extends Base
{
	/**
	 * 初始化
	 */
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(203001);
	}
	/**
	 * 获取订单列表
	 * @return [type] [description]
	 */
	public function list(){
		$data = input('get.');
		$data = init_where($data);
		$list = HawaList::usergetlist($data,'acco');
		foreach ($list['list'] as $key => $value) {
			if(empty($value['companyinfo']['Name'])){
				$list['list'][$key]['Name'] = '暂未完善名称';
			}else{
				$list['list'][$key]['Name'] = $value['companyinfo']['Name'];
			}
		}
		$list['tr']['title']  = ['产废单位','下单时间','订单状态','查看','结算时间','订单费用'];
		$list['tr']['key'] = ['Name','UpTime','State','HawaListId','SettlementTime','TotalCost'];
		$list['tr']['show'] = [true, true, true, true, true, true];
		return myok($list);
	}
	/**
	 * 获取订单信息
	 * @return [type] [description]
	 */
	public function getinfo(){
		$id = input('id');
		if(empty($id)){
			return myerr('缺少参数，请重新尝试');
		}
		$data = HawaList::getinfo($id,'acco');
		if(!$data['code']){
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		$data['CELLPHONE'] = CELLPHONE;
		return myok($data);
	}
	/**
	 * 结算订单
	 * @return [type] [description]
	 */
	public function settlement(){
		$id = input('id');
		$data = HawaList::liststate($id);
		if(empty($data)){
			return myerr('没有找到需要的订单');
		}
		$data = $data['msg'];

		$rdata = [];
		$rdata['id'] = $id;
		if(!empty(input('SettlementImg'))){
			$rdata['SettlementImg']  = input('SettlementImg');
		}
		if(!empty(input('SettlementNote'))){
			$rdata['SettlementNote']  = input('SettlementNote');
		}
		if(!empty(input('autocost'))&&input('autocost')!=='false'&&empty($data['SettlementTime'])){
			$cost = $data['TotalCost'];
			if(empty($cost)){
		        return myerr('费用为空无需记录');
			}
			$sdata['TypeId'] = Costtype::getid('orderhawa');
		    $sdata['PayTime'] = date("Y-m-d H:i",time());
		    $sdata['RelationUserId'] = '';
		    $sdata['RelationListId'] = $id;
		    if(!empty(input('SettlementImg'))){
				$sdata['UpImg'] = input('SettlementImg');
			}
			if(!empty(input('SettlementNote'))){
				$sdata['UpNote']   = input('SettlementNote');
			}
			if($cost>0){
		        $sdata['PayCost'] = $cost;
				Revenue::screate($sdata);
			}else{
				$sdata['PayCost'] = 0 - $cost;
				Pay::screate($sdata);
			}
		}
		$rdata['SettlementTime'] = date('Y-m-d H:i',time());
		HawaList::user_reinfo($rdata);
		//检查结算账单是否一致
		if(!empty($data['SettlementTime'])){
			return myok('已修改结算备注');
		}else{
			$sb = Sendmessage::Orderhawa(6,$id,$data);
			if(!$sb['code']){
				return myok('已结算,'.$sb['msg']);
			}
			return myok('已结算');
		}
	}

	/**
	 * 挂账订单结算
	 * @return [type] [description]
	 */
	public function revenue_account_period_settlement(){
		$id = input('id');
		$data = HawaList::liststate($id);
		if(empty($data)){
			return myerr('没有找到需要的订单');
		}
		$data = $data['msg'];
		$rdata = [];
		$rdata['id'] = $id;

		$cost = input('Price');
		if($cost>$data['TotalCost']){
			return myerr('提交失败：实际支付费用，超过订单总费用');
		}
		// dump($data['TotalCost']);exit;
		if(empty($data['TotalCost'])||(int)$data['TotalCost']==0){
		   return myerr('费用为空无需记录');
		}
		//添加挂账记录信息
		$RAPListId = Raplist::create('orderhawa',$id,$cost,input('Img'),input('Note'),input('ExpectedTime'),input('SettlementTime'));
		//添加支出/收入表
		if(!empty($cost)&&input('autocost')!=='false'){
			$sdata['TypeId'] = Costtype::getid('orderhawa');
		     $sdata['PayTime'] = date("Y-m-d H:i",time());
		     $sdata['RelationUserId'] = '';
		     $sdata['RelationListId'] = $id;
		    if(!empty(input('Img'))){
				$sdata['UpImg'] = input('Img');
			}
			if(!empty(input('Note'))){
				$sdata['UpNote']   = input('Note');
			}
			if($cost>0){
		          $sdata['PayCost'] = $cost;
				Revenue::screate($sdata);
			}else{
				$sdata['PayCost'] = 0 - $cost;
				Pay::screate($sdata);
			}
		}
		$rdata['SettlementTime'] = date('Y-m-d H:i',time());
		// $rdata['State'] = Contract::STATEOK;
		$rdata['RAPListId'] = $RAPListId;
		HawaList::user_reinfo($rdata);
		//检查结算账单是否一致
		if(!empty($data['SettlementTime'])){
			return myok('已修改挂账备注信息');
		}else{
			$sb = Sendmessage::Orderhawa(6,$id,$data);
			if(!$sb['code']){
				return myok('已结算,'.$sb['msg']);
			}
			return myok('已结算');
		}
	}

	/**
	 * 图片上传
	 * @return [type] [description]
	 */
	public function upimg(){
		$type = empty(input('type'))?'other':input('type');
		if(!$type=='hawa'||!$type=='buss'||!$type=='acco'){
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status'=>'error','data'=>$e->getMessage()]);
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\hawa\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>SERVERURL.'static/upimg/hawa/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}

         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}


	/**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}
}
